package entity

import (
	"fmt"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"

	"github.com/jinzhu/gorm"
)

//SJZL 数据治理
type SJZL struct {
	ID       int     `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	BBNO     string  `gorm:"column:BBNO"`
	BBMC     string  `gorm:"-" `
	WTMS     string  `gorm:"column:WTMS"`
	JCHF     string  `gorm:"column:JCHF"`
	UID      int     `gorm:"column:UID"`
	WFID     int     `gorm:"column:WFID"`
	FRID     int     `gorm:"column:FRID"`
	Progress float64 `gorm:"-" json:"progress"`
	StepName string  `gorm:"-" json:"stepName"`
	Status   string  `gorm:"-" json:"status"`
	STEP     int     `gorm:"-" json:"step"`
}

//TableName User用户表名
func (SJZL) TableName() string {
	return "T_CONF_SJZL"
}

//BeforeSave 保存前的触发器
func (i *SJZL) BeforeSave(tx *gorm.DB) (err error) {

	if i.ID > 0 {
		row := base.DB.Model(SJZL{}).Where("ID=?", i.ID).Select("FRID").Row()
		row.Scan(&i.FRID)
	}
	if i.FRID == 0 {
		runid, err := workflow.Create(6, i.UID, tx)
		if err != nil {
			return err
		}
		i.FRID = runid
	}
	return
}

func (i *SJZL) AfterDelete(tx *gorm.DB) (err error) {
	if i.FRID > 0 {
		return workflow.DeleteWithTx(i.FRID, tx)
	}
	return nil
}

//AfterFind 查询后触发器
func (i *SJZL) AfterFind(tx *gorm.DB) (err error) {
	row := tx.Raw("select PermissionName from T_Permission where ID= ?", i.BBNO).Row()
	row.Scan(&i.BBMC)

	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}
	return
}

func SJZLEF() base.EntityFunc {
	return func() interface{} {
		entity := SJZL{}
		return &entity
	}
}
func SJZLESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SJZL
		return &entities
	}
}

func init() {
	dao := base.NewDefaultDao(SJZLEF(), SJZLESF(), nil)
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", "6")
	dao.Fileter = &filter
	base.DaoPoolObj.Put("SJZL", dao)
}
